<?php
require 'core.inc.php';
require 'connect.inc.php';



if (!loggedin()) 
{
	if 
	(isset($_POST['emailaddr'])&& isset($_POST['password'])&& isset($_POST['confirm_password'])&& 
	 isset($_POST['firstname'])&& isset($_POST['lastname']))
	{
		$emailaddr = $_POST['emailaddr'];
		$password = $_POST['password'];
		$confirm_password = $_POST['confirm_password'];
		$firstname = $_POST['firstname'];
		$lastname = $_POST['lastname'];
		
		if (!empty($emailaddr)&&!empty($password)&&!empty($confirm_password) &&
			!empty($firstname)&&!empty($lastname))
		{
			if ($password==$confirm_password)
			{
				$password_md5 = md5($password);
				$query = "SELECT `emailaddress` FROM `users` WHERE `emailaddress`='$emailaddr'";
				$query_run = mysql_query($query);
				
				if (mysql_num_rows($query_run)==1)
				{
					echo 'The email address '.$emailaddr.' is already registered.';
				}
				else
				{
				
					$query = "INSERT INTO `users` VALUES ( '', 
					'".mysql_real_escape_string($firstname)."',
					'".mysql_real_escape_string($lastname)."', 
					'".mysql_real_escape_string($password_md5)."', 
					'".mysql_real_escape_string($emailaddr)."')";
					
					//echo $query;
					//echo <br>;
				
					if ($query_run = mysql_query($query))
					{
						
						$query = "SELECT `id`, `firstname` FROM `users` WHERE `emailaddress`='$emailaddr'";
						$query_run = mysql_query($query);
						$_SESSION['user_id'] = mysql_result($query_run, 0, 'id');
						$_SESSION['firstname'] = mysql_result($query_run, 0, 'firstname');
						
						header('Location: register_success.php');
					}
					else
					{
						echo 'Registration Failed. Please Try again later.';
					}
					
				}
			}
			else
			{
				echo 'Please re-enter your password.';
			}
			
		}
	}
	else
	{
	echo 'Please fill in all fields';
	}
?>

<form action="register.php" method="POST">
Email Address:<br> <input type="text" name="emailaddr"><br><br>
Password:<br> <input type="password" name="password"><br><br>
Confirm Password:<br> <input type="password" name="confirm_password"><br><br>
Firstname:<br> <input type="text" name="firstname"><br><br>
Surname:<br> <input type="text" name="lastname"><br><br>
<input type="submit" value="Register">
</form>

<?php
}else
{
	echo 'You\'re already logged in';
}

?>